// 左边开启拖动
$(".initial_option").draggable({
    helper: "clone",
    pcope: "pdd",
    cursor: "move",
    cursorAt: { top: 50, left: 50},
    // 限制拖拽范围
    containment: "#flow_box",
    // 元素从左边拖动时
    drag: function(ev) {
		console.log("不要停")
    }
});
// 右边放置
var ling = 0;
$("#flow_right").droppable({
    pcope: "pdd",
    drop: function (event,ui){
        let L = parseInt(ui.offset.left - $(this).offset().left);
        console.log(L);
        let T = parseInt(ui.offset.top - $(this).offset().top);
        if(L<0) L=10;if(T<10) T=10;
        let name = ui.draggable[0].id;
        let pid = "";
        switch (name)
        {
            case 'proposer_node':
                ling++;
                name = '申请人';
                pid = 'proposer_node'+ling;
                break;
            case 'examine_node':
                ling++;
                name = '审批节点'
                pid = 'examine_node'+ling;
                break;
            case 'write_node':
                ling++;
                name = '填写节点'
                pid = 'write_node'+ling;
                break;
            case 'copy_node':
                ling++;
                name = '抄送节点'
                pid = 'copy_node'+ling;
                break;
            case 'branch_node':
                ling++;
                name = '分支'
                pid = 'branch_node'+ling;
                break;
        }
        var pnode = `<div class='new_node' id='${pid}' style='top: ${T}px;left: ${L}px'>
						<p>${name}</p>
						<span class='node_delete' data-pid='${pid}'>X</span>
						<span class="node_set glyphicon glyphicon-cog" data-pid='${pid}'></span>
					</div>`;
        //添加进右侧
        $(this).append(pnode);
        jsPlumb.ready(function (){
            jsPlumb.addEndpoint(pid,{anchors: "TopCenter", uuid:pid+"1"},LineStyle);
            jsPlumb.addEndpoint(pid,{anchors: "RightMiddle", uuid:pid+"2"},LineStyle);
            jsPlumb.addEndpoint(pid,{anchors: "BottomCenter", uuid:pid+"3"},LineStyle);
            jsPlumb.addEndpoint(pid,{anchors: "LeftMiddle", uuid:pid+"4"},LineStyle);
        })
        //开启拖拽并限制范围
        jsPlumb.draggable(pid,{
            containment: 'flow_box',
            stop:function () {
                console.log("拖动停止了");
            }
        });
    }
});
// 鼠标进入和移出新节点时显示删除和设置按钮
$("#flow_right").on("mouseenter",".new_node",function(){
    let pid = $(this).attr("id");
    $(".node_delete[data-pid="+pid+"]").css("display","block");
    $(".node_set[data-pid="+pid+"]").css("display","block");
}).on("mouseleave",".new_node",function(){
    let pid = $(this).attr("id");
    $(".node_delete[data-pid="+pid+"]").css("display","none");
    $(".node_set[data-pid="+pid+"]").css("display","none");
})
// 点击删除按钮删除节点
$("#flow_right").on("click",".node_delete",function(ev){
    ev.stopPropagation();
    let pid = $(this).data("pid");
    if(confirm("确认删除该节点及连线吗？")){
        $("#"+pid).remove();
        jsPlumb.removeAllEndpoints(pid);
    }
})
// 双击节点修改文字
$("#flow_right").on("dblclick",".new_node",function(){
    let text = $(this).children("p").text();
    $(this).children("p").remove();
    $(this).append("<input type='text' class='form-control'/>");
    $(this).children("input").focus();
    $(this).children("input").val(text);
    $(this).children("input").blur(function(){
        let text = $(this).val();
        $(this).parent().append('<p>'+text+'</p>')
        $(this).remove();
    })
})
// 双击删除连线
jsPlumb.bind('dblclick', function (conn,originalEvent) {
    if (confirm('确定删除所点击的连线吗？')){
        jsPlumb.deleteConnection(conn);
    }
});
// 点击连线中间加号出现小菜单
$("#flow_right").on("click",".event_node",function(ev){
    ev.stopPropagation();
    // 获取当前的中点的id
    let Thisid = $(this)[0].id;
    let dialog = `<ul class='dialog'>
                    <li class='dialog_option' data-id='${Thisid}'><span class='glyphicon glyphicon-cog'></span>我是选项</li>
                    <li class='dialog_option' data-id='${Thisid}'><span class='glyphicon glyphicon-envelope'></span>我是选项</li>
                    <li class='dialog_option' data-id='${Thisid}'><span class='glyphicon glyphicon-user'></span>我是选项</li>
                    <li class='dialog_option' data-id='${Thisid}'><span class='glyphicon glyphicon-file'></span>我是选项</li>
                    <li class='dialog_option' data-id='${Thisid}'><span class='glyphicon glyphicon-lock'></span>我是选项</li>
                </ul>`;
    // 添加小菜单
    $("#"+Thisid).append(dialog);
    // 判断、如果是在底部打开菜单、就从上方出现
    if($(window).height()-$("#"+Thisid).offset().top<200){
        $(".dialog").css("top","-200px")
    }
    // 清除小菜单
    $("#flow_right").one("click",function(){
        $(".dialog").remove();
    })
})
// 点击设置按钮出现右侧菜单
$("#flow_right").on("click",".node_set",function(){
    let text = $(this).parent().children("p").text();
    let list = `<div id='shade'>
                    <div id='shade_left'></div>
                    <div id='shade_list'>
                        <div class='shade_title'>
                            <b>${text}</b>
                        </div>
                    </div>
                </div>`;
    $("#flow_box").append(list);
    $("#shade_list").animate({"width":"50%"},200);
})
// 删除右侧遮罩层和菜单
$("#flow_box").on("click","#shade_left",function(){
    $("#shade").remove();
})
// 点击保存
$(".flow_save").click(function(){
    localStorage.removeItem("ling");
    localStorage.setItem('ling',ling);
    save();
    alert("保存成功");
})
// 点击删除
$(".flow_delete").click(function(){
    localStorage.removeItem("ligature");
    localStorage.removeItem("node");
    localStorage.removeItem("ling");
    alert("清除成功");
})
//页面加载时识别缓存JSON
window.onload = function(){
    ling = localStorage.getItem('ling');
    if(localStorage.getItem('ligature')){
        let ligature = JSON.parse(localStorage.getItem('ligature'));
        let node = JSON.parse(localStorage.getItem('node'));
        // 节点的模板渲染
        let html_node = `<script type="text/x-jsrender" id="html_node">
                            <div class='new_node' id='{{:BlockId}}' style='top: {{:BlockY}}px;left: {{:BlockX}}px'>
                                {{:BlockContent}}
                            </div>
                        </script>`
        if($('#html_node').length===0) $("body").append(html_node);
        var pnode = $('#html_node').render(node);
        $("#flow_right").append(pnode);
        // 将节点的端点还原
        for(let i = 0;i<node.length;i++){
            jsPlumb.ready(function (){
                jsPlumb.addEndpoint(node[i].BlockId,{anchors: "TopCenter",uuid:node[i].BlockId+"1"},LineStyle);
                jsPlumb.addEndpoint(node[i].BlockId,{anchors: "RightMiddle",uuid:node[i].BlockId+"2"},LineStyle);
                jsPlumb.addEndpoint(node[i].BlockId,{anchors: "BottomCenter",uuid:node[i].BlockId+"3"},LineStyle);
                jsPlumb.addEndpoint(node[i].BlockId,{anchors: "LeftMiddle",uuid:node[i].BlockId+"4"},LineStyle);
                jsPlumb.draggable(node[i].BlockId,{
                    containment: 'flow_box',
                    stop:function () {
                        console.log("拖动停止了");
                    }
                });
            })
        }
        // 将节点的连线还原
        for(let i = 0;i<ligature.length;i++){
            jsPlumb.ready(function (){
                jsPlumb.connect({uuids:[ligature[i].Uuids[0],ligature[i].Uuids[1]]},LineStyle);
            })
        }
    }
}
// 右侧连线图存储为JSON的方法
function save() {
    // 端点和连线数据
    var connects = [];
    $.each(jsPlumb.getAllConnections(), function (idx,connection) {
        connects.push({
            ConnectionId: connection.id,
            PageSourceId: connection.sourceId,
            PageTargetId: connection.targetId,
            Uuids: connection.getUuids()
        });
    });
    // dom节点数据
    var blocks = [];
    $("#flow_right .new_node").each(function (idx,elem) {
        var $elem = $(elem);
        blocks.push({
            BlockId: $elem.attr('id'),
            // 将 " 换成 '
            BlockContent: $elem.html().replace(/"/g,"'"),
            BlockX: parseInt($elem.css("left"), 10),
            BlockY: parseInt($elem.css("top"), 10)
        });
    });
    // 解决获取html后的换行符空格问题
	for(let i = 0;i<blocks.length;i++){
		blocks[i].BlockContent = blocks[i].BlockContent.replace(/[\t\n]/g,"");
	}
	console.log(blocks)
	// 将数据转换格式后存储
    let ligature = JSON.stringify(connects);
    // 将多出来的 \ 去掉
    let node = JSON.stringify(blocks).replace(/\\/g,"");
    localStorage.setItem('ligature',ligature);
    localStorage.setItem('node',node);
    console.log("ligature："+ligature)
    console.log("node："+node)
}